<?php
/**
 * 云盘系统安装引导
 */

$error = '';
$success = '';

if ($_POST) {
    // 接收配置数据
    $db_host = trim($_POST['db_host'] ?? '');
    $db_name = trim($_POST['db_name'] ?? '');
    $db_user = trim($_POST['db_user'] ?? '');
    $db_pass = trim($_POST['db_pass'] ?? '');
    $db_port = trim($_POST['db_port'] ?? '3306');

    // 管理员信息
    $admin_user = trim($_POST['admin_user'] ?? '');
    $admin_pass = trim($_POST['admin_pass'] ?? '');
    $admin_pass2 = trim($_POST['admin_pass2'] ?? '');

    // 验证输入
    if (empty($db_host) || empty($db_name) || empty($db_user)) {
        $error = '请填写完整的数据库信息';
    } elseif (empty($admin_user) || empty($admin_pass)) {
        $error = '请设置管理员账号和密码';
    } elseif ($admin_pass !== $admin_pass2) {
        $error = '两次输入的密码不一致';
    } elseif (strlen($admin_pass) < 6) {
        $error = '密码长度不能少于6位';
    } else {
        try {
            // 测试数据库连接
            $dsn = "mysql:host={$db_host};port={$db_port};charset=utf8mb4";
            $pdo = new PDO($dsn, $db_user, $db_pass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            ]);

            // 创建数据库
            $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$db_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            $pdo->exec("USE `{$db_name}`");

            // 创建文件表
            $files_sql = "
                CREATE TABLE IF NOT EXISTS files (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    original_name VARCHAR(255) NOT NULL,
                    stored_name VARCHAR(255) NOT NULL,
                    file_path VARCHAR(500) NOT NULL,
                    file_size BIGINT NOT NULL,
                    file_type VARCHAR(100),
                    file_ext VARCHAR(10),
                    upload_time DATETIME DEFAULT CURRENT_TIMESTAMP,
                    download_count INT DEFAULT 0,
                    delete_code VARCHAR(32),
                    direct_link VARCHAR(64) UNIQUE,
                    file_title VARCHAR(255) NULL COMMENT '文件标题',
                    file_description TEXT NULL COMMENT '文件描述',
                    page_title VARCHAR(255) NULL COMMENT '页面标题',
                    page_description TEXT NULL COMMENT '页面描述',
                    INDEX idx_upload_time (upload_time)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
            ";
            $pdo->exec($files_sql);

            // 创建管理员表
            $admin_sql = "
                CREATE TABLE IF NOT EXISTS admins (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    username VARCHAR(50) UNIQUE NOT NULL,
                    password VARCHAR(255) NOT NULL,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
            ";
            $pdo->exec($admin_sql);

            // 创建管理员账号
            $hashed_pass = password_hash($admin_pass, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO admins (username, password) VALUES (?, ?)");
            $stmt->execute([$admin_user, $hashed_pass]);

            // 写入配置文件
            $config_content = "<?php
// 数据库配置
define('DB_HOST', '{$db_host}');
define('DB_NAME', '{$db_name}');
define('DB_USER', '{$db_user}');
define('DB_PASS', '{$db_pass}');
define('DB_PORT', {$db_port});

// 网站配置
define('SITE_URL', '');
define('SITE_NAME', 'ORBIAI工作室云盘');
define('MAX_FILE_SIZE', 100 * 1024 * 1024); // 100MB

// 文件存储路径
define('UPLOAD_DIR', __DIR__ . '/../uploads/');

// 管理员配置
define('ADMIN_USERNAME', '{$admin_user}');
define('ADMIN_PASSWORD', '{$admin_pass}'); // 管理员密码明文，用于删除文件验证

// 安全配置
define('CSRF_TOKEN', 'cloudbox_' . md5(__DIR__));

session_start();

if (!isset(\$_SESSION['csrf_token'])) {
    \$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// 检查管理员登录
if (!isset(\$_SESSION['admin_logged_in'])) {
    \$_SESSION['admin_logged_in'] = false;
}
";

            // 如果config.php存在则备份
            if (file_exists(__DIR__ . '/config/config.php')) {
                copy(__DIR__ . '/config/config.php', __DIR__ . '/config/config.php.bak');
            }

            file_put_contents(__DIR__ . '/config/config.php', $config_content);

            // 创建安装锁
            file_put_contents(__DIR__ . '/config/installed.lock', date('Y-m-d H:i:s'));

            // 确保uploads目录可写
            if (!is_dir(__DIR__ . '/uploads')) {
                mkdir(__DIR__ . '/uploads', 0755, true);
            }

            $success = '安装成功！管理员账号：' . htmlspecialchars($admin_user) . '<br>3秒后自动跳转到首页...';
            header("Refresh: 5; url=index.php");

        } catch (Exception $e) {
            $error = '安装失败: ' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>云盘系统安装</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            width: 100%;
            max-width: 520px;
            padding: 40px;
        }

        .logo {
            text-align: center;
            margin-bottom: 30px;
        }

        .logo h1 {
            color: #667eea;
            font-size: 32px;
            font-weight: 700;
            margin-bottom: 8px;
        }

        .logo p {
            color: #666;
            font-size: 14px;
        }

        .error, .success {
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .error {
            background: #fee;
            color: #c33;
            border: 1px solid #fcc;
        }

        .success {
            background: #efe;
            color: #3c3;
            border: 1px solid #cfc;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
            font-size: 14px;
        }

        .form-group input {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
        }

        .btn {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .info {
            margin-top: 20px;
            padding: 12px;
            background: #f5f5f5;
            border-radius: 8px;
            font-size: 12px;
            color: #666;
        }

        .step {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
        }

        .step-number {
            width: 32px;
            height: 32px;
            background: #667eea;
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
        }

        .step-text {
            color: #333;
            font-weight: 500;
        }

        .section-title {
            color: #667eea;
            font-size: 18px;
            font-weight: 600;
            margin: 30px 0 15px 0;
            padding-top: 20px;
            border-top: 2px solid #f0f0f0;
        }

        .section-title:first-of-type {
            margin-top: 0;
            padding-top: 0;
            border-top: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="logo">
            <h1>☁️ 个人云盘</h1>
            <p>简单、安全、高效的文件存储</p>
        </div>

        <?php if ($error): ?>
            <div class="error"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="success"><?= $success ?></div>
        <?php endif; ?>

        <form method="post" action="">
            <div class="step">
                <div class="step-number">1</div>
                <div class="step-text">数据库配置</div>
            </div>

            <div class="form-group">
                <label>数据库地址</label>
                <input type="text" name="db_host" value="localhost" placeholder="localhost">
            </div>

            <div class="form-group">
                <label>数据库端口</label>
                <input type="text" name="db_port" value="3306" placeholder="3306">
            </div>

            <div class="form-group">
                <label>数据库名称</label>
                <input type="text" name="db_name" value="cloudbox" placeholder="cloudbox">
            </div>

            <div class="form-group">
                <label>数据库用户名</label>
                <input type="text" name="db_user" placeholder="root">
            </div>

            <div class="form-group">
                <label>数据库密码</label>
                <input type="password" name="db_pass" placeholder="输入密码（可为空）">
            </div>

            <div class="section-title">
                <div class="step">
                    <div class="step-number">2</div>
                    <div class="step-text">管理员设置</div>
                </div>
            </div>

            <div class="form-group">
                <label>管理员用户名</label>
                <input type="text" name="admin_user" placeholder="admin" required>
            </div>

            <div class="form-group">
                <label>管理员密码</label>
                <input type="password" name="admin_pass" placeholder="至少6位" required>
            </div>

            <div class="form-group">
                <label>确认密码</label>
                <input type="password" name="admin_pass2" placeholder="再次输入密码" required>
            </div>

            <button type="submit" class="btn">开始安装</button>
        </form>

        <div class="info">
            <strong>提示：</strong><br>
            1. 确保数据库服务已启动<br>
            2. 用户需要有创建数据库的权限<br>
            3. 安装后请删除此安装文件<br>
            4. 请妥善保管管理员账号和密码
        </div>
    </div>
</body>
</html>
